# http://127.0.0.1:8000/meiduo_admin/users/?page=3&&pagesize=1
from rest_framework.generics import ListAPIView
from rest_framework.permissions import IsAdminUser, DjangoModelPermissions
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet

from apps.goods.models import SKU, GoodsCategory, SPU, SPUSpecification, SpecificationOption
from apps.meiduo_admin.serializers.sku import SKUSerializer, GoodsCategoryModelSerializer, SPUModelSerializer, \
    SpecsModelSerializer
from apps.meiduo_admin.utils import PageNum


class SKUModelViewSet(ModelViewSet):
    # 1指定查询集
    # queryset = User.objects.all()
    # 2指定序列化器
    serializer_class = SKUSerializer

    # 添加分页类
    pagination_class = PageNum

    # 登录 和查看
    # DjangoModelPermissions
    permission_classes = [IsAdminUser, DjangoModelPermissions]

    # - 1查询 所有用户
    # - 2 把数据转为字典 （序列化器）
    # - 3 返回数据

    def get_queryset(self):
        # 返回查询集
        # 获取前端 传来的 keyword参数

        keyword = self.request.query_params.get('keyword')
        # 判断是否有搜索内容
        if keyword:
            return SKU.objects.filter(name__contains=keyword)

        return SKU.objects.all()


class GoodsCategoryListAPIView(ListAPIView):
    # 1指定查询集  filter(subs=None) 只获取第三级
    queryset = GoodsCategory.objects.filter(subs=None)
    # 2指定序列化器
    serializer_class = GoodsCategoryModelSerializer


# 获取所有spu
class SPUListAPIView(ListAPIView):
    # 1指定查询集
    queryset = SPU.objects.all()
    # 2指定序列化器
    serializer_class = SPUModelSerializer


# 获取所有spu规格  前端发送过来了 spu_id  /goods/2/specs/  /goods/<spu_id>/specs/

class SPUSpecificationAPIView(APIView):

    def get(self, request, spu_id):
        # 1 根据spu_id获取所有规格
        specs = SPUSpecification.objects.filter(spu_id=spu_id)

        # for s in specs:
        # 遍历所有的规格 查询每个规格下所有的选项
        # options = SpecificationOption.objects.filter(spec_id=s.id)

        # 使用序列化器 注意 是多个数据many=True
        specsSerializer = SpecsModelSerializer(specs, many=True)
        return Response(specsSerializer.data)
